#include "Thread.hpp"
#include <vector>

using namespace ThreadModule;

pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;

void MasterCore(int n) // for write (cond_signal)
{
    for (int i = 0; i < n; i++)
    {
        std::cout << "===== Master: send awake signal to slave =====" << std::endl;
        //pthread_cond_signal(&g_cond);
        pthread_cond_broadcast(&g_cond);
        sleep(5);
    }
}

void SlaveCore(const std::string &name) // for read (cond_wait)
{
    int i = 0;

    pthread_mutex_lock(&g_mutex);

    // wait the singal from Master
    std::cout << name << " -> Slave: sleep~~~" << std::endl;
    pthread_cond_wait(&g_cond, &g_mutex);
    std::cout << name << " -> Slave: i am wake now\n" << std::endl;

    pthread_mutex_unlock(&g_mutex);
}

int main()
{
    const int n = 10;
    std::vector<Thread> thread_v;
    thread_v.reserve(n);

    // Create master thread
    Thread("master-thread", MasterCore, n);

    // Create slave threads
    for (int i = 0; i < n; ++i)
    {
        std::string name = "thread-" + std::to_string(i + 1);
        sleep(2);
        Thread(name, SlaveCore, name);
    }
    
    sleep(20);  // wait for all thread
    return 0;
}
